package main

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var (
	bashdir = ""
	in      io.WriteCloser
)

func main() {
	file, err := os.Open("./cmds.toml")
	if os.IsNotExist(err) {
		file, err = os.Create("./cmds.toml")
		if err != nil {
			fmt.Println(err)
		}
	}

	tree := NewTOMLTree(file)
	comment := tree.GetString("comment")
	printOptions(tree, comment, 0)
}

func printOptions(tree *Object, title string, level int) {

	for {
		fmt.Println(commentBeautify(title))
		fmt.Println("--------------------------------------------------------------------------------------------")

		i := 1
		options := []string{}
		options = append(options, "返回")
		for _, key := range tree.Keys {
			child := tree.GetOject(key)
			if child != nil {
				od := ""
				if 'a'+i-1 <= 'z' {
					od = string('a' + i - 1)
				}
				fmt.Printf("%v  %c[0;32m%v%c[0m\n", od, 0x1B, key, 0x1B)
				options = append(options, key)
				i++

				comment := commentBeautify(child.GetString("comment"))
				if len(comment) > 0 {
					fmt.Printf("   %v\n", comment)
				}
			}
		}

		if level > 0 {
			fmt.Println("0  返回上一层")
		}

		var order int
		for {
			var orderstr string
			fmt.Scanln(&orderstr)
			if len(orderstr) > 0 {
				or := rune(orderstr[0])
				if or == '0' {
					order = 0
				} else {
					order = int(or + 1 - 'a')
				}
			}

			if order > len(tree.Keys) {
				fmt.Println("输入选项错误,请重新输入")
			} else {
				break
			}
		}

		if order <= 0 {
			return
		} else if len(options) > order {
			idx := options[order]
			child := tree.GetOject(idx)

			if checkCmd(child) {
				format := child.GetString("format")
				if len(format) > 0 {
					cmd := exec.Command(format)
					cmd.Stdin = os.Stdin
					cmd.Stdout = os.Stdout
					cmd.Stderr = os.Stderr
					err4 := cmd.Run()
					fmt.Println(err4)
				}
			} else {
				printOptions(child, idx, level+1)
			}
		}
	}
}

func checkCmd(t *Object) bool {
	for _, key := range t.Keys {
		child := t.GetOject(key)
		if child != nil {
			return false
		}
	}
	return true

}

func printCmd(cmd string) {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	dir = strings.Replace(dir, "\\", "/", -1)

	fmt.Printf("shorthand:%v$ %v", dir, cmd)

}

func commentBeautify(comment string) string {
	comment = strings.TrimSpace(comment)
	if len(comment) <= 0 {
		return ""
	}
	comment = strings.Replace(comment, "\\r\\n", "\n", -1)
	//comment = strings.Replace(comment, "\\r", "", -1)
	return comment
}
